type MessageCallback = (data: any) => void;

class PluginWebSocketClient {
    private static instance: PluginWebSocketClient;
    private ws: WebSocket = null as any;
    private url: string = "ws://localhost:3000";
    private callbacks: MessageCallback[] = [];

    private constructor() {
        this.connect();
    }

    public static getInstance(): PluginWebSocketClient {
        if (!PluginWebSocketClient.instance) {
            PluginWebSocketClient.instance = new PluginWebSocketClient();
        }
        return PluginWebSocketClient.instance;
    }

    private connect() {
        this.ws = new WebSocket(this.url);

        this.ws.onopen = () => {
            console.log("[Plugin] Connected to Platform");
        };

        this.ws.onmessage = (event) => {
            const data = JSON.parse(event.data);
            console.log("[Plugin] Received:", data);
            this.callbacks.forEach((cb) => cb(data)); // 通知所有回调
        };

        this.ws.onclose = () => {
            console.log("[Plugin] Disconnected, reconnecting...");
            setTimeout(() => this.connect(), 1000);
        };
    }

    // 发送请求到平台（请求-响应模式）
    public sendRequest(request: any): Promise<any> {
        return new Promise((resolve, reject) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                reject(new Error("WebSocket not connected"));
                return;
            }

            // 注册一次性回调
            const handler = (data: any) => {
                if (data.success) {
                    resolve(data);
                } else {
                    reject(new Error(data.error || "Unknown error"));
                }
                this.offMessage(handler); // 移除回调
            };

            this.onMessage(handler);
            this.ws.send(JSON.stringify(request));
        });
    }

    // 注册消息回调（接收平台主动推送的事件）
    public onMessage(callback: MessageCallback) {
        this.callbacks.push(callback);
    }

    // 移除消息回调
    public offMessage(callback: MessageCallback) {
        this.callbacks = this.callbacks.filter((cb) => cb !== callback);
    }
}

export default PluginWebSocketClient;